package com.sita.bike.ui.activity.roadtrust;

import android.app.ProgressDialog;
import android.content.res.Configuration;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMapOptions;
import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyTrafficStyle;
import com.sita.bike.R;
import com.sita.bike.persistence.Route;
import com.sita.bike.persistence.RouteData;
import com.sita.bike.rest.RestClient;
import com.sita.bike.rest.model.RestResponse;
import com.sita.bike.rest.model.UploadRouteResponseData;
import com.sita.bike.rest.model.UploadRouteHeaderParams;
import com.sita.bike.support.Constants;
import com.sita.bike.support.GlobalContext;
import com.sita.bike.utils.AccountUtils;
import com.sita.bike.utils.FormatUtils;
import com.sita.bike.utils.MapUtils;
import com.sita.bike.utils.PersistUtils;
import com.sita.bike.utils.ShareUtils;
import com.sita.bike.utils.TracksInfoUtils;
import com.sita.tboard.util.ZipUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;
import retrofit.mime.TypedString;

public class RouteFinishStatusActivity extends AppCompatActivity {

    private AMap aMap;
    private TextureMapView mapView;
    private UiSettings mUiSettings;
    private long mTrackId;
    private long mTime;
    private float mMileage;
    private TextView mTvTime;
    private TextView mTvMileage;
    private TextView mTvAverSpeed;
    private TextView mTvMileages;
    private ImageView mImgBack;
    private ImageView mImgShare;
    private long mRouteServerId;
    private float averSpeed;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_route_finish_status);
        mapView = (TextureMapView) findViewById(R.id.route_finish_map);
        mapView.onCreate(savedInstanceState);// 此方法必须重写
        initMap();

        Bundle bundle = this.getIntent().getExtras();
        mTime = bundle.getLong("time");
        mMileage = bundle.getFloat("mileage");
        mTrackId = bundle.getLong("trackId");


        mTvMileage = (TextView) findViewById(R.id.speed_over_distance_value);
        mTvMileage.setText(FormatUtils.formatDistance2(mMileage));

        mTvMileages = (TextView) findViewById(R.id.tv_mileages);
        mTvMileages.setText(FormatUtils.formatDistance2(mMileage));

        mTvTime = (TextView) findViewById(R.id.speed_over_time_value);
        mTvTime.setText(FormatUtils.formatShortTimeHHMM(mTime));

        mTvAverSpeed = (TextView) findViewById(R.id.speed_over_speed_value);
        averSpeed = mMileage / mTime * 1000f;
        mTvAverSpeed.setText(FormatUtils.formatSpeedString(averSpeed));

        mImgBack = (ImageView) findViewById(R.id.speed_over_back);
        mImgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doBack();
            }
        });

        mImgShare = (ImageView) findViewById(R.id.route_share);
        mImgShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                doShare();
            }
        });

        drawTrackTask.execute();

        final ProgressDialog mProgressDialog = new ProgressDialog(this);
        String str = getResources().getString(R.string.is_sync_track_list);
        mProgressDialog.setMessage(str);
        mProgressDialog.setCanceledOnTouchOutside(false);
        mProgressDialog.show();

        TracksInfoUtils.uploadTrack(null, new TracksInfoUtils.UploadTrackListener() {
            @Override
            public void Success(long routeId) {
                mRouteServerId = routeId;
                mProgressDialog.dismiss();
            }

            @Override
            public void Fail() {
                mProgressDialog.dismiss();
            }
        }, mTrackId);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    private void doBack() {
        this.finish();
    }

    private void doShare() {
        ShareUtils.doShareRoute(mRouteServerId, FormatUtils.formatDistance2(mMileage), this, this);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (mapView != null) {
            mapView.onResume();
        }

    }

    @Override
    public void onPause() {
        if (mapView != null) {
            mapView.onPause();
        }
        super.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    @Override
    public void onDestroy() {
        if (mapView != null) {
            mapView.onDestroy();
            aMap = null;
        }
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onStop() {
        super.onStop();
    }


    private void initMap() {

        if (aMap == null) {
            aMap = mapView.getMap();
            setMapUi();
        }
//        aMap.setMapType(AMap.MAP_TYPE_NIGHT);
        setTraffic();

        AMapLocation location = GlobalContext.getLocationClient().getLastKnownLocation();
        LatLng latLng = (location == null) ? null : new LatLng(location.getLatitude(), location.getLongitude());
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target((latLng == null) ? Constants.DEFAULT_LATLNG : latLng)
                .zoom(Constants.DEFAULT_ZOOM_LEVEL).bearing(0).tilt(0).build();
        CameraUpdate update = CameraUpdateFactory.newCameraPosition(cameraPosition);
        aMap.moveCamera(update);

    }

    private void setMapUi() {
        mUiSettings = aMap.getUiSettings();
        mUiSettings.setZoomControlsEnabled(false);
        mUiSettings.setLogoPosition(AMapOptions.LOGO_POSITION_BOTTOM_LEFT);
        mUiSettings.setScrollGesturesEnabled(true);
    }

    private void setTraffic() {
        MyTrafficStyle myTrafficStyle = new MyTrafficStyle();
        myTrafficStyle.setSeriousCongestedColor(0xff92000a);
        myTrafficStyle.setCongestedColor(0xffea0312);
        myTrafficStyle.setSlowColor(0xffff7508);
        myTrafficStyle.setSmoothColor(0xff00a209);
        aMap.setTrafficEnabled(false);
    }

    private AsyncTask drawTrackTask = new AsyncTask() {
        @Override
        protected Object doInBackground(Object[] params) {
            MapUtils.displayTrack(mTrackId, aMap);
            return null;
        }
    };

    private AsyncTask uploadTrackTask = new AsyncTask() {
        File originalFile = null;
        File zipFile = null;

        @Override
        protected Object doInBackground(Object[] params) {
            //构造json，压缩上传数据
            List<RouteData> gpsLocationList = PersistUtils.getRouteDataList(mTrackId);
            FileOutputStream fileOutputStream = null;
            try {
                originalFile = new File(Environment.getExternalStorageDirectory(), mTrackId + ".json");
                fileOutputStream = new FileOutputStream(originalFile);
                if (!originalFile.exists()) {
                    originalFile.createNewFile();
                }
                String title = "[";
                fileOutputStream.write(title.getBytes());
                String separator = "";
                for (RouteData g : gpsLocationList) {
                    fileOutputStream.write(separator.getBytes());
                    String oneLocationPoint = "{" + " \"longitude\":" + g.getLongitude() + "," +
                            "\"latitude\": " + g.getLatitude() + "," +
                            "\"speed\": " + g.getSpeed() + "," +
                            "\"rpm\": " + 0 + "," +
                            "\"time\": " + g.getTime() +
                            "}";
                    fileOutputStream.write(oneLocationPoint.getBytes());
                    separator = ",";
                }
                String end = "]";
                fileOutputStream.write(end.getBytes());
                fileOutputStream.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fileOutputStream != null) {
                        fileOutputStream.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            zipFile = new File(Environment.getExternalStorageDirectory(), mTrackId + ".zip");
            try {
                if (!zipFile.exists()) {
                    zipFile.createNewFile();
                }
                ZipUtils.zipFile(originalFile, zipFile);
                //上传，监听成功后，删除两个文件
            } catch (IOException e) {
                e.printStackTrace();
            }

            TypedFile uploadFile = (zipFile.equals("")) ? null : new TypedFile("zip", zipFile);
            UploadRouteHeaderParams uploadRouteHeaderParams = new UploadRouteHeaderParams();
            final Route tracks = PersistUtils.getRoute(mTrackId);
            uploadRouteHeaderParams.mStartTime = tracks.getStartTime();
            uploadRouteHeaderParams.mEndTime = tracks.getEndTime();
            TypedString uploadParams = new TypedString(RestClient.getGson().toJson(uploadRouteHeaderParams));
            RestClient.getRestService().uploadRoadTrust(AccountUtils.getAccountID(), uploadParams, uploadFile, new Callback<RestResponse>() {
                @Override
                public void success(RestResponse restResponse, Response response) {
                    if (originalFile.isFile() && originalFile.exists()) originalFile.delete();
                    if (zipFile.isFile() && zipFile.exists()) zipFile.delete();
                    String s = RestClient.getGson().toJson(restResponse.mData);
                    UploadRouteResponseData uploadRouteResponseData = RestClient.getGson().fromJson(s, UploadRouteResponseData.class);
                    mRouteServerId = uploadRouteResponseData.mRouteId;
                    tracks.setServerRouteId(String.valueOf(mRouteServerId));
                    PersistUtils.updateRoute(tracks);
                }
                @Override
                public void failure(RetrofitError error) {
                    tracks.setFilePath(zipFile.getPath());
                    PersistUtils.updateRoute(tracks);
                }
            });
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);

        }
    };

}
